import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { verifySession } from '@/lib/auth/dal';
import { fetchCommonCodes } from '@/lib/data/repositories/common-code-repository';
import {
  fetchMerchantDetail,
  fetchMerchantSummary,
} from '@/lib/data/repositories/merchant-detail-repository';
import { fetchMerchantProducts } from '@/lib/data/repositories/merchant-product-repository';
import { CODE_GROUP } from '@/lib/domain/common-code';
import { MerchantDetailForm } from './_components/merchant-detail-form';

export const metadata: Metadata = { title: '가맹몰 상세 정보' };
export const dynamic = 'force-dynamic';

interface PageProps {
  params: Promise<{ frcsNo: string }>;
}

/**
 * 가맹점 하나의 상세 화면. 상세가 있으면 고치고, 없으면(백엔드 단건이 NOT_FOUND — develop은 빈 가맹점
 * 행을 주므로 `hasDetail`로 한 번 더 거른다) 가맹점 목록에서 찾아 그 가맹점을 고정한 채 처음 만든다.
 */
export default async function Page({ params }: PageProps) {
  await verifySession();

  const { frcsNo } = await params;
  const categoriesPromise = fetchCommonCodes(CODE_GROUP.merchantType);
  const detail = await fetchMerchantDetail(frcsNo);

  if (!detail || !detail.hasDetail) {
    const merchant = await fetchMerchantSummary(frcsNo);
    if (!merchant) {
      notFound();
    }
    return <MerchantDetailForm merchant={merchant} categories={await categoriesPromise} />;
  }

  const [products, categories, badgeCodes, merchant] = await Promise.all([
    fetchMerchantProducts(frcsNo),
    categoriesPromise,
    fetchCommonCodes(CODE_GROUP.merchantProductBadge),
    // 상세 응답에 업체명이 빠지는 백엔드 결함 — 코드만 왔으면 가맹점 목록에서 이름을 채운다.
    detail.name === detail.id ? fetchMerchantSummary(frcsNo) : Promise.resolve(null),
  ]);
  return (
    <MerchantDetailForm
      detail={merchant ? { ...detail, name: merchant.name } : detail}
      products={products}
      categories={categories}
      badgeCodes={badgeCodes}
    />
  );
}
